{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 层次遍历二叉树\n",
    "\n",
    "广度优先搜索算法（英语：Breadth-First-Search，缩写为BFS），又译作宽度优先搜索，或横向优先搜索，是一种图形搜索算法。\n",
    "\n",
    "简单的说，BFS是从根节点开始，沿着树的宽度遍历树的节点。\n",
    "\n",
    "如果所有节点均被访问，则算法中止。\n",
    "\n",
    "\n",
    "<img src=\"./bread_visit_tree.png\" style=\"margin-left:0px; width:400px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node(object):\n",
    "    def __init__(self, data, left=None, right=None):\n",
    "        self.data = data\n",
    "        self.left = left\n",
    "        self.right = right"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tree = Node(\n",
    "    1, \n",
    "    Node(\n",
    "        2, \n",
    "        Node(4),\n",
    "        Node(5,Node(7), Node(8))),\n",
    "    Node(3, \n",
    "         Node(6))\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def level_visit(root):\n",
    "    # 使用列表模拟queue\n",
    "    queue = [root]\n",
    "    while queue:\n",
    "        # 删除list的最开始的元素\n",
    "        current = queue.pop(0)\n",
    "        print(current.data, end=\",\")\n",
    "        if current.left:\n",
    "            queue.append(current.left)\n",
    "        if current.right:\n",
    "            queue.append(current.right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1,2,3,4,5,6,7,8,"
     ]
    }
   ],
   "source": [
    "level_visit(tree)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
